<template>
  <div>
    <h3>V3的购物车</h3>
    <div class="table">
      <div class="tr">
        <div class="td">
          全选
          <input
            type="checkbox"
            :checked="data.checkedAll"
            @change="setCheckedAll"
          />
        </div>
        <div class="td">名称</div>
        <div class="td">价格</div>
        <div class="td">数量</div>
        <div class="td">小计</div>
        <div class="td">操作</div>
      </div>

      <div class="tr" v-for="item in data.list" :key="item.id">
        <div class="td">
          <input type="checkbox" v-model="item.checked" />
        </div>
        <div class="td">
          {{ item.goodsname }}
        </div>
        <div class="td">
          {{ item.goodsprice }}
        </div>
        <div class="td">
          <button v-show="item.goodsnum > 1" @click="calc(item, -1)">-</button>
          {{ item.goodsnum }}
          <button @click="calc(item, 1)">+</button>
        </div>
        <div class="td">
          {{ item.goodsnum * item.goodsprice }}
        </div>
        <div class="td" @click="delById(item.id)">删除</div>
      </div>
      <div class="tr">
        <div class="td"></div>
        <div class="td"></div>
        <div class="td"></div>
        <div class="td">数量{{ num }}</div>
        <div class="td">小计{{ price }}</div>
        <div class="td"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from "vue";
let data = ref({
  checkedAll: false,
  list: [
    {
      id: 1,
      goodsname: "商品一",
      goodsprice: 100,
      goodsnum: 1,
      checked: false,
    },
    {
      id: 2,
      goodsname: "商品二",
      goodsprice: 200,
      goodsnum: 2,
      checked: false,
    },
    {
      id: 3,
      goodsname: "商品三",
      goodsprice: 300,
      goodsnum: 3,
      checked: false,
    },
  ],
});
let calc = (item, num) => {
  item.goodsnum = item.goodsnum + num;
};
let price = computed(() => {
  let checkList = data.value.list.filter((item) => item.checked);
  if (checkList.length) {
    return checkList
      .map((item) => item.goodsnum * item.goodsprice)
      .reduce((a, b) => a + b);
  }
  return 0;
});

let num = computed(() => {
  //计算属性
  let checkedList = data.value.list.filter((item) => item.checked);
  if (checkedList.length) {
    return checkedList.map((item) => item.goodsnum).reduce((a, b) => a + b);
  }
  return 0;
});
let setCheckedAll = (e) => {
  data.value.list.forEach((item) => {
    item.checked = e.target.checked;
  });
};
watch(
  [data],
  () => {
    data.value.checkedAll = data.value.list.length
      ? data.value.list.every((item) => item.checked)
      : false;
  },
  { deep: true }
); //深度监听
let delById = (id) => {
  data.value.list = data.value.list.filter((item) => item.id !== id);
};
</script>
<style scoped>
.table {
  width: 100%;
}
.tr {
  display: flex;
}
.tr .td {
  flex: 1;
  text-align: center;
  line-height: 40px;
  color: black;
}
</style>
